package io.wins.vertx.verticle.api;

import io.vertx.core.Future;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.wins.vertx.entity.Root;
import io.wins.vertx.service.RootService;

public class RootApiVerticle extends RestApiVerticle {

    public static final String ROOT_REST_ADDRESS = "io.wins.rest.root#%1$s";
    public static final String CREATE_ROOT = "createRoot";
    public static final String UPDATE_ROOT = "updateRoot";
    public static final String DELETE_ROOT = "deleteRoot";
    public static final String LIST_ROOT = "listRoot";
    public static final String LOAD_ROOT = "loadRoot";
    private static final Logger logger = LoggerFactory.getLogger(RootApiVerticle.class);

    public final RootService service;

    public RootApiVerticle(final RootService rootService) {
        this.service = rootService;
    }

    @Override
    public void start(final Future<Void> startFuture) throws Exception {
        super.start();
        this.on(String.format(ROOT_REST_ADDRESS, CREATE_ROOT), this::createRoot);
        this.on(String.format(ROOT_REST_ADDRESS, LIST_ROOT), this::listRoot);
        this.on(String.format(ROOT_REST_ADDRESS, UPDATE_ROOT), this::updateRoot);
        startFuture.complete();
    }

    private void listRoot(final Message<JsonObject> tMessage) {
        final JsonObject param = tMessage.body().getJsonObject("param");
        this.service.listRoot(tMessage);
    }

    private void createRoot(final Message<JsonObject> tMessage) {
        final JsonObject body = tMessage.body().getJsonObject("body").getJsonObject("root");
        final Root root = new Root(body);
        this.service.createRoot(root, tMessage);
    }
    private void updateRoot(final Message<JsonObject> tMessage) {
        final JsonObject body = tMessage.body().getJsonObject("body").getJsonObject("root");
        final Root root = new Root(body);
        this.service.updateRoot(root, tMessage);
    }
}
